﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.RuleEngine;
using System.IO;

namespace A2DFramework.BusinessExceptionService.JavascriptGenerator
{
    class BusinessExceptionServiceJavascriptGenerator : IJavascriptGenerator
    {
        private string ruleContent;
        private string field;
        private string errorMessage;

        public BusinessExceptionServiceJavascriptGenerator(string ruleContent, string field, string errorMessage)
        {
            this.ruleContent = ruleContent;
            this.field = field;
            this.errorMessage = errorMessage;
        }
        

        public string GenerateJS()
        {
            string js = "";
            js = this.GeneratePreservedJS() + "\r\n" + this.GenerateJudgeJS(ruleContent);
            return js;
        }

        private string GenerateJudgeJS(string ruleContent)
        {
            string js = string.Empty;

            js += "var result=true;";
            js += "\r\n";
            js += string.Format(@"if (!({0}))", ruleContent);
            js += "\r\n";
            js += "{";
            js += "\r\n";
            //js += string.Format(@"              helper.addErrorMessage(""{0}"", ""{1}"");", this.field, this.errorMessage);
            //js += "\r\n";
            js += "                             result=false;";
            js += "\r\n";
            js += "}";
            js += "\r\n";
            return js;
        }

        private string GeneratePreservedJS()
        {
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RuleEngine", "jsLib", "underscore-min.js");
            string libJsContent = File.ReadAllText(path);
            return libJsContent + "\r\n\r\n\r\n";
        }
    }
}
